<template>
  <el-dialog
    v-model="dialogVisible"
    title="脚本详情"
    width="80%"
    :close-on-click-modal="false"
  >
    <div v-if="script" class="script-detail">
      <!-- 脚本基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <div class="header-actions">
              <el-tag :type="getStatusType(script.status)">
                {{ getStatusText(script.status) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>脚本名称：</label>
              <span>{{ script.name }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>关联需求：</label>
              <span>{{ script.requirement_title || '无' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatTime(script.created_at) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>更新时间：</label>
              <span>{{ formatTime(script.updated_at) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item">
          <label>脚本描述：</label>
          <p class="description">{{ script.description || '无描述' }}</p>
        </div>
        
        <div v-if="script.tags" class="info-item">
          <label>标签：</label>
          <div class="tags">
            <el-tag
              v-for="tag in getTagArray(script.tags)"
              :key="tag"
              size="small"
              style="margin-right: 8px;"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </el-card>

      <!-- YAML脚本内容 -->
      <el-card class="yaml-card">
        <template #header>
          <div class="card-header">
            <span>YAML脚本内容</span>
            <div class="header-actions">
              <el-button size="small" @click="copyYaml">
                <el-icon><DocumentCopy /></el-icon>
                复制
              </el-button>
              <el-button size="small" @click="validateYaml">
                <el-icon><CircleCheck /></el-icon>
                验证
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="yaml-content">
          <CodeHighlight language="yaml" :code="script.yaml_content" />
        </div>
      </el-card>

      <!-- 执行统计 -->
      <el-card class="stats-card">
        <template #header>
          <span>执行统计</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ script.execution_count || 0 }}</div>
              <div class="stat-label">总执行次数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number success">{{ getSuccessCount() }}</div>
              <div class="stat-label">成功次数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number danger">{{ getFailedCount() }}</div>
              <div class="stat-label">失败次数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ getSuccessRate() }}%</div>
              <div class="stat-label">成功率</div>
            </div>
          </el-col>
        </el-row>
        
        <div v-if="script.last_execution_time" class="last-execution">
          <label>最近执行：</label>
          <span>{{ formatTime(script.last_execution_time) }}</span>
          <el-tag
            :type="getExecutionStatusType(script.last_execution_status)"
            size="small"
            style="margin-left: 8px;"
          >
            {{ getExecutionStatusText(script.last_execution_status) }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
        <el-button type="success" @click="handleExecute">
          <el-icon><VideoPlay /></el-icon>
          执行
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, CircleCheck, Edit, VideoPlay, Delete } from '@element-plus/icons-vue'
import { validateYamlScript } from '../../api/uiAutomation'
import CodeHighlight from '../../components/CodeHighlight.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  script: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'edit', 'execute', 'delete'])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 方法
const handleClose = () => {
  dialogVisible.value = false
}

const handleEdit = () => {
  emit('edit', props.script)
  dialogVisible.value = false
}

const handleExecute = () => {
  emit('execute', props.script)
  dialogVisible.value = false
}

const handleDelete = () => {
  emit('delete', props.script)
  dialogVisible.value = false
}

const copyYaml = async () => {
  try {
    await navigator.clipboard.writeText(props.script.yaml_content)
    ElMessage.success('YAML内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

const validateYaml = async () => {
  if (!props.script?.yaml_content) {
    ElMessage.warning('YAML内容为空')
    return
  }
  
  try {
    const response = await validateYamlScript(props.script.yaml_content)
    if (response.success) {
      ElMessage.success('YAML脚本格式验证通过')
    } else {
      ElMessage.error(`YAML脚本格式错误: ${response.message}`)
    }
  } catch (error) {
    console.error('验证YAML失败:', error)
    ElMessage.error('验证YAML失败')
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'draft': '',
    'active': 'success',
    'inactive': 'info'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'active': '激活',
    'inactive': '停用'
  }
  return statusMap[status] || status
}

const getExecutionStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'running': 'warning',
    'success': 'success',
    'failed': 'danger',
    'cancelled': ''
  }
  return statusMap[status] || ''
}

const getExecutionStatusText = (status) => {
  const statusMap = {
    'pending': '待执行',
    'running': '执行中',
    'success': '成功',
    'failed': '失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getTagArray = (tags) => {
  if (!tags) return []
  return tags.split(',').filter(tag => tag.trim())
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

const getSuccessCount = () => {
  // 这里应该从实际的执行统计数据获取
  return 0
}

const getFailedCount = () => {
  // 这里应该从实际的执行统计数据获取
  return 0
}

const getSuccessRate = () => {
  const total = getSuccessCount() + getFailedCount()
  if (total === 0) return 0
  return Math.round((getSuccessCount() / total) * 100)
}
</script>

<style lang="scss" scoped>
.script-detail {
  .info-card,
  .yaml-card,
  .stats-card {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    
    .header-actions {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
  
  .info-item {
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 600;
      color: #303133;
      margin-right: 8px;
    }
    
    span {
      color: #606266;
    }
    
    .description {
      margin: 8px 0 0 0;
      color: #606266;
      line-height: 1.6;
    }
    
    .tags {
      margin-top: 4px;
    }
  }
  
  .yaml-content {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .stat-item {
    text-align: center;
    
    .stat-number {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      line-height: 1;
      margin-bottom: 4px;
      
      &.success {
        color: #67c23a;
      }
      
      &.danger {
        color: #f56c6c;
      }
    }
    
    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
  
  .last-execution {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
    
    label {
      font-weight: 600;
      color: #303133;
      margin-right: 8px;
    }
    
    span {
      color: #606266;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 8px;
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>
